class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def bstToGst(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        st = [root]
        now_sum = 0
        while st[-1].right:
            st.append(st[-1].right)
        while st:
            node = st.pop()
            now_sum += node.val
            node.val = now_sum
            if node.left:
                node = node.left
                while node:
                    st.append(node)
                    node = node.right
        return root
